from src.model import Message

from datetime import datetime
from datetime import timedelta
from base import BaseHandler
from src.utilities.prefetcher import prefetch_refprop
from src.utilities.cache import memoize
import time


class LiveHandler(BaseHandler):
	NETWORK_LAG_TIME = 10 #seconds
	MAX_MESSAGES_PER_UPDATE = 100
	OPTIMIZATION_GAP = 2 # increase to better performance
	
	@staticmethod
	@memoize('live_update_%d')
	def cached_content(timestamp, self):
		return self.content()

	def content(self):
		interval = self.request.get('interval')
		update_interval = (int(interval) if interval != '' else 30) + LiveHandler.NETWORK_LAG_TIME
		date = datetime.now() - timedelta(seconds = update_interval)
		messages = Message.all().order('-changed').filter('changed >', date).fetch(LiveHandler.MAX_MESSAGES_PER_UPDATE, 0)
		prefetch_refprop(messages, Message.person)

		return self.generate_template('messages.json', {
				'messages':messages
		})    
	
	def get(self):
		timestamp = int(time.time())
		timestamp = timestamp - (timestamp % LiveHandler.OPTIMIZATION_GAP)
		content = LiveHandler.cached_content(timestamp, self)
		self.write_response(content, content_type='application/json')
